﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;


namespace ManageTicket.Human
{
    public partial class frmUsers : frmBase
    {
        #region Contructor
        public frmUsers()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Users boUsers = new Business.Users();
        private Business.UsersRole boUsersRole = new Business.UsersRole();
        private Business.Employee boEmployee = new Business.Employee();
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        #endregion

        #region Event
        private void frmUsers_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật người sử dụng";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_16");

            LoadGroup();

            //set status
            LoadStatusOnce();

            View();
        }

        private void lvwUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                sModel = "";
                IsEdit();
                if (lvwUsers.SelectedItems.Count > 0)
                {
                    DataObjects.Users oUser = boUsers.GetObjectByPK(lvwUsers.SelectedItems[0].Text);
                    if (oUser != null)
                    {
                        txtUserId.Text = oUser.UserId;
                        string pass = objMethod.Decrypt(oUser.Password);
                        pass = pass.Substring(oUser.UserId.Length, pass.Length - oUser.UserId.Length);
                        pass = pass.Substring(0, pass.Length - oUser.EmployeeId.Length);
                        txtPassword.Text = pass;
                        txtEmployeeId.Text = oUser.EmployeeId;
                        DataObjects.Employee oEmp = boEmployee.GetObjectByPK(oUser.EmployeeId);
                        if (oEmp != null)
                            txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;
                        FillGroup(oUser.UserId);

                        LoadStatus(true, true, true, false, false, true);
                    }
                    
                }
                else
                {
                    LoadStatus(true, false, false, false, false, true);
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        
        private void txtEmployeeId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oCus != null)
                {
                    txtFullName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtFullName.Focus();
                }
            }
        }
        #endregion

        #region Execute
        public override void Add()
        {
            objMethod.ClearText(new Control[] { txtUserId, txtPassword, txtEmployeeId, txtFullName });
            ClearGroup();
            LoadStatus(false, false, false, true, true, false);
            lvwUsers.Enabled = false;
            sModel = ADD_MODEL;
            IsEdit();
            txtUserId.Focus();
        }

        public override void Edit()
        {
            if (txtUserId.Text == "")
                return;
            LoadStatus(false, false, false, true, true, false);
            lvwUsers.Enabled = false;
            sModel = UPDATE_MODEL;
            IsEdit();
            txtPassword.Focus();
        }

        public override void Delete()
        {
            try
            {
                if (txtUserId.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete
                    boUsers.DeleteByPK(txtUserId.Text);

                    MessageBox.Show("Xóa user thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    View();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            objMethod.ClearText(new Control[] { txtUserId, txtPassword, txtEmployeeId, txtFullName });
            ClearGroup();
            LoadStatus(false, false, false, false, false, true);
            View();
        }

        public override void Save()
        {
            if (txtUserId.Text == "")
            {
                return;
            }
            if (CheckValid())
            {
                try
                {
                    DataObjects.Users oUsers = new DataObjects.Users();
                    oUsers.UserId = txtUserId.Text;
                    oUsers.Password = objMethod.Encrypt(txtUserId.Text + txtPassword.Text + txtEmployeeId.Text);
                    oUsers.EmployeeId = txtEmployeeId.Text;

                    if (txtUserId.ReadOnly)
                    {
                        //update
                        boUsers.Update(oUsers);
                    }
                    else
                    {
                        //insert
                        if (CheckIsExist(oUsers.UserId))
                        {
                            MessageBox.Show("Tên người sử dụng cấp đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtUserId.Focus();
                            return;
                        }
                        boUsers.Insert(oUsers);
                    }
                    SaveGroup(oUsers.UserId);
                    txtUserId.ReadOnly = true;
                    MessageBox.Show("Cập nhật người sử dụng thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    View();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật người sử dụng.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public override void View()
        {
            try
            {
                lvwUsers.Items.Clear();

                ArrayList arrGroup = new ArrayList();
                arrGroup = boUsers.List();

                ListViewItem item;

                foreach (DataObjects.Users oUser in arrGroup)
                {
                    item = new ListViewItem();
                    item.Text = oUser.UserId;
                    lvwUsers.Items.Add(item);
                }

                if (lvwUsers.Items.Count > 0)
                {
                    lvwUsers.Items[0].Selected = true;
                    lvwUsers.Enabled = true;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Method
        private void LoadStatusOnce()
        {
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnFind.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blEdit, bool blDelete, bool blCancel, bool blSave, bool blView)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnEdit.Enabled = blEdit & bEdit;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnView.Enabled = blView & bView;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnEdit.ButtonColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = exeCtrl.btnView.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnEdit.ForeColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = exeCtrl.btnView.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void IsEdit()
        {
            if (sModel == ADD_MODEL)
            {
                txtUserId.ReadOnly = false;
                txtPassword.ReadOnly = false;
                txtEmployeeId.ReadOnly = false;
                lvwGroup.Enabled = true;
            }
            else if (sModel == UPDATE_MODEL)
            {
                txtUserId.ReadOnly = true;
                txtPassword.ReadOnly = false;
                txtEmployeeId.ReadOnly = false;
                lvwGroup.Enabled = true;
            }
            else
            {
                txtUserId.ReadOnly = true;
                txtPassword.ReadOnly = true;
                txtEmployeeId.ReadOnly = true;
                lvwGroup.Enabled = false;
            }
        }

        private bool CheckValid()
        {
            if (txtUserId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tên đăng nhập.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserId.Focus();
                return false;
            }
            else if (!objMethod.CheckSpecialCharacter(txtUserId.Text))
            {
                MessageBox.Show("Tên đăng nhập không được nhập các ký tự đặc biệt.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserId.Focus();
                return false;
            }

            if (txtPassword.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập mật khẩu.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return false;
            }

            if (txtEmployeeId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhân viên.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmployeeId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oCus == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmployeeId.Focus();
                    return false;
                }
            }
            if (lvwGroup.CheckedItems.Count == 0)
            {
                MessageBox.Show("Vui lòng chọn nhóm.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lvwGroup.Focus();
                return false;
            }
            return true;
        }

        private void ClearGroup()
        {
            foreach (ListViewItem item in lvwGroup.Items)
            {
                item.Checked = false;
            }
        }

        private void LoadGroup()
        {
            Business.UsersGroup boGroup = new Business.UsersGroup();
            ArrayList arr = boGroup.List();
            if (arr != null)
            {
                if (arr.Count > 0)
                {
                    lvwGroup.Items.Clear();
                    ListViewItem item;
                    foreach (DataObjects.UsersGroup oGroup in arr)
                    {
                        item = new ListViewItem();
                        item.Tag = oGroup.GroupId;
                        item.Text = oGroup.GroupName;
                        lvwGroup.Items.Add(item);
                    }
                }
            }
        }

        private void FillGroup(string userId)
        {
            ClearGroup();
            ArrayList arr = boUsersRole.GetListByUserId(userId);
            if (arr != null)
            {
                if (arr.Count > 0)
                {
                    foreach (DataObjects.UsersRole oUserRole in arr)
                    {
                        foreach (ListViewItem item in lvwGroup.Items)
                        {
                            if (oUserRole.GroupId == item.Tag.ToString())
                            {
                                item.Checked = true;
                            }
                        }
                    }
                }
            }
        }

        private void SaveGroup(string userId)
        {
            //delete
            boUsersRole.DeleteByUserId(userId);

            //insert
            DataObjects.UsersRole oUserRole;
            foreach (ListViewItem item in lvwGroup.CheckedItems)
            {
                oUserRole = new DataObjects.UsersRole();
                oUserRole.UserId = userId;
                oUserRole.GroupId = item.Tag.ToString();
                boUsersRole.Insert(oUserRole);
            }
        }

        private bool CheckIsExist(string id)
        {
            DataObjects.Users oUser = boUsers.GetObjectByPK(id);
            if (oUser != null)
            {
                return true;
            }
            return false;
        }
        #endregion

    }
}
